//
//  UIAlertController.swift
//  fho
//
//  Created by 郭颢源 on 2021/3/31.
//

import Foundation
import SnapKit

extension UIAlertController {

    public convenience init(customView : UIView, closure:@escaping (_ make: ConstraintMaker) -> Void){
        self.init(title:nil, message:nil, preferredStyle: UIAlertController.Style.alert)
        view.clipsToBounds = false

        customView.tag = 1111
        view.addSubview(customView)

        // 这里需要加一个action 不然会报错
        let action = UIAlertAction(title:"", style: .default, handler:nil)
        addAction(action)

        //约束
        customView.snp.makeConstraints { (make) in
            closure(make)
        }

        // 隐藏系统的View
        _ = self.view.subviews.compactMap { (view) -> Void in
            if view.tag != 1111 {
                view.isHidden = true
            }else {
                view.isHidden = false
            }
        }
    }



    public func show(animated: Bool = true, style: UIBlurEffect.Style? = nil, completion: (() -> Void)? = nil) {
        
        if let style = style {
            for subView in view.subviews {
                if subView.isKind(of: UIVisualEffectView.self) {
                    let sub = subView as! UIVisualEffectView
                    sub.effect = UIBlurEffect(style: style)
                }
            }
        }

        DispatchQueue.main.async {
//            UIApplication.shared.keyWindow?.rootViewController?.present(self, animated: animated, completion: completion)
            UIApplication.shared.windows.first?.rootViewController?.present(self, animated: animated, completion: completion)
        }
    }
    @discardableResult
    func addAlertAction(withTitle title: String?, style: UIAlertAction.Style = .default, handler: ((UIAlertAction) -> Void)?) -> Self {
        addAction(UIAlertAction(title: title, style: style, handler: handler))

        return self
    }
}
